package org.zgjy;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.ModbusRequest;
import com.serotonin.modbus4j.msg.ModbusResponse;
import org.zgjy.model.Device;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class DevicePeer {

    public Device device;

    private IpParameters ipParameters;
    private ModbusFactory modbusFactory;

    private ModbusMaster master;

    public DevicePeer(Device device) {
        this.device = device;
    }

    public void initial_modbus(){

        if(this.device.ip.equals("") || this.device.port == 0){
            return ;
        }

        if(this.ipParameters == null){
            this.ipParameters = new IpParameters();
            this.ipParameters.setHost(this.device.ip);
            this.ipParameters.setPort(this.device.port);
        }

        if( this.modbusFactory == null){
            this.modbusFactory = new ModbusFactory();
        }

        if(this.master == null){
            this.master = modbusFactory.createTcpMaster(ipParameters, false);
            master.setTimeout(4000);
            master.setRetries(1);
        }
    }

    public ModbusResponse send(ModbusRequest request) throws ModbusTransportException {
        return this.master.send(request);
    }

    public boolean test_connectivity(){

        boolean connectivity = false;
        Socket s = new Socket();
        try{
            s.connect(new InetSocketAddress(this.device.ip, this.device.port), 3000);
            connectivity = true;
        }catch (IOException e){
            System.out.println(e);
        }finally {
            try{
                s.close();
            }catch (IOException e){
                System.out.println(e);
            }
        }
        return connectivity;
    }
}
